<template>
    <div class="page">
        <gzg-search :config="searchConfig" 
                    :form="searchForm"
                    :show-more="false"
                    :label-width="120"
                    @search="search"></gzg-search>
        <div class="grid-wrap">
            <el-table style="width:100%;"
                              height="100%"
                              :border="true"
                              :data="listData.data">
                <el-table-column label="序号" type="index" width="60px" fixed="left"></el-table-column>
                <el-table-column label="商户信息" width="250px">
                    <template #default="props">
                        <div>
                            <div>ID:{{ props.row.seller_id }}</div>
                            <div>商户全称:{{ props.row.company_name || '-' }}</div>
                            <div>商户简称:{{ props.row.short_name || '-' }}</div>
                            <div>商家支付宝:{{ props.row.alipay_account || '-' }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="支付开通" min-width="150px">
                    <template #default="props">
                        <div>
                            <div>事务编号:{{ props.row.pay_work_no || '-' }}</div>
                            <div style="display: flex;align-items: center;">
                                <span>状态:{{ props.row.pay_status_desc || '-' }}</span>
                                <el-tooltip v-if="props.row.pay_refuse_reason"
                                        :content="`拒绝原因:${ props.row.pay_refuse_reason }`"
                                        placement="top">
                                    <el-button size="small" type="danger" style="margin-left: 10px;">原因</el-button>
                                </el-tooltip>
                            </div>
                            <div>提交时间:{{ props.row.pay_put_at || '-' }}</div>
                            <div>授权时间:{{ props.row.pay_auth_at || '-' }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="分账开通" min-width="150px">
                    <template #default="props">
                        <div>
                            <div>事务编号:{{ props.row.royalty_work_no || '-' }}</div>
                            <div style="display: flex;align-items: center;">
                                <span>状态:{{ props.row.royalty_status_desc || '-' }}</span>
                                <el-tooltip v-if="props.row.royalty_refuse_reason"
                                        :content="`拒绝原因:${ props.row.royalty_refuse_reason }`"
                                        placement="top">
                                    <el-button size="small" type="danger" style="margin-left: 10px;">原因</el-button>
                                </el-tooltip>
                            </div>
                            <div>提交时间:{{ props.row.royalty_put_at || '-' }}</div>
                            <div>授权时间:{{ props.row.royalty_auth_at || '-' }}</div>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="操作" width="326px" fixed="right">
                    <template #default="props">
                        <div>
                            <el-button :type="props.row.is_set_auth ? 'primary' : 'danger'" @click="openAuthDialog(props.row)" v-if="props.row.button.app_auth_btn" link>应用授权</el-button>
                            <el-button type="primary" @click="openPayDialog(props.row)" v-if="props.row.button.open_pay_btn" link>开通支付</el-button>
                            <el-button type="primary" @click="openRoyaltyDialog(props.row)" v-if="props.row.button.open_royalty_btn" link>开通分账</el-button>
                            <el-button :type="props.row.is_set_royalty ? 'primary' : 'danger'" @click="openRoyaltyRateDialog(props.row)" v-if="props.row.button.set_royalty_btn" link>分账比例</el-button>
                            <el-button :type="props.row.huabei_status == 1 ? 'danger' : 'primary'" @click="openPeriodDialog(props.row)" v-if="props.row.button.period_set_btn" link>花呗分期</el-button>

                        </div>
                    </template>
                </el-table-column> -->
            </el-table>
        </div>
        <div class="page-wrap">
            <el-pagination
                v-model:current-page="params.page"
                v-model:page-size="params.page_size"
                :page-sizes="[100, 200, 300, 400]"
                layout="total, prev, pager, next"
                :total="listData.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <el-dialog title="应用授权" v-model="authDialogState" width="580px">
            <el-form ref="authFormRef" :model="form" :rules="formRules" label-width="120px">
                <el-form-item label="商家名称:">
                    <div>{{ form.company_name }}</div>
                </el-form-item>
                <el-form-item label="支付宝商家PID:" prop="merchant_pid">
                    <el-input v-model="form.merchant_pid" placeholder="一般是2088开头"></el-input>
                </el-form-item>
                <el-form-item label="授权应用appid:" prop="auth_app_id">
                    <el-input v-model="form.auth_app_id" placeholder="一般是2021开头"></el-input>
                </el-form-item>
                <el-form-item label="授权token" prop="auth_token">
                    <el-input v-model="form.auth_token" placeholder="请输入授权token"></el-input>
                </el-form-item>
                <div class="desc" style="font-size: 12px;color:#f56c6c">如上信息请务核查填写正确，不能将商家A的信息添写到商家B，否则会导致商家收款错乱！</div>
                <div class="desc" style="font-size: 12px;color:#f56c6c">商家正式使用前，请运营务必下单测试确认，收银台收款方是否正确！</div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="authDialogState = false">取 消</el-button>
                    <el-button type="primary" @click="saveAuth(authFormRef)">确 定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog title="开通支付" v-model="payDialogState" width="580px">
            <el-form ref="payFormRef" :model="form" :rules="formRules" label-width="150px">
                <el-form-item label="H5网站地址:" prop="h5_web_url">
                    <el-input v-model="form.h5_web_url" placeholder="请输入H5网站地址"></el-input>
                </el-form-item>
                <el-form-item label="网站备注:" prop="web_remark">
                    <el-input type="textarea" v-model="form.web_remark" placeholder="请输入网站备注"></el-input>
                </el-form-item>
                <el-form-item label="H5网站首页截图:" prop="h5_home_screenshot">
                    <el-upload
                        v-model:file-list="h5_home_screenshot_list"
                        :action="baseUrl + 'v1/tools/file/upload'"
                        list-type="picture-card"
                        accept=".png,.gif,.jpeg,.jpg"
                        :headers="{
                            'x-token': token,
                        }"
                        :data="{
                            module: 'seller_file',
                        }"
                        :limit="1"
                        :with-credentials="true"
                        :on-remove="(res) => {
                            handleImgRemove(res, 'h5_home_screenshot')
                        }"
                        :on-success="(res) => {
                            handleImgSuccess(res, 'h5_home_screenshot');
                        }">
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="H5网站商品截图:" prop="h5_item_screenshot">
                    <el-upload
                        v-model:file-list="h5_item_screenshot_list"
                        :action="baseUrl + 'v1/tools/file/upload'"
                        list-type="picture-card"
                        accept=".png,.gif,.jpeg,.jpg"
                        :headers="{
                            'x-token': token,
                        }"
                        :data="{
                            module: 'seller_file',
                        }"
                        :limit="1"
                        :with-credentials="true"
                        :on-remove="(res) => {
                            handleImgRemove(res, 'h5_item_screenshot')
                        }"
                        :on-success="(res) => {
                            handleImgSuccess(res, 'h5_item_screenshot');
                        }">
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="H5网站支付页截图:" prop="h5_pay_screenshot">
                    <el-upload
                        v-model:file-list="h5_pay_screenshot_list"
                        :action="baseUrl + 'v1/tools/file/upload'"
                        list-type="picture-card"
                        accept=".png,.gif,.jpeg,.jpg"
                        :headers="{
                            'x-token': token,
                        }"
                        :data="{
                            module: 'seller_file',
                        }"
                        :limit="1"
                        :with-credentials="true"
                        :on-remove="(res) => {
                            handleImgRemove(res, 'h5_pay_screenshot')
                        }"
                        :on-success="(res) => {
                            handleImgSuccess(res, 'h5_pay_screenshot');
                        }">
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="网站备注图片:" prop="h5_extra_pic">
                    <el-upload
                        v-model:file-list="h5_extra_pic_list"
                        :action="baseUrl + 'v1/tools/file/upload'"
                        list-type="picture-card"
                        accept=".png,.gif,.jpeg,.jpg"
                        :headers="{
                            'x-token': token,
                        }"
                        :data="{
                            module: 'seller_file',
                        }"
                        :limit="1"
                        :with-credentials="true"
                        :on-remove="(res) => {
                            handleImgRemove(res, 'h5_extra_pic')
                        }"
                        :on-success="(res) => {
                            handleImgSuccess(res, 'h5_extra_pic');
                        }">
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="payDialogState = false">取 消</el-button>
                    <el-button type="primary" @click="savePay(payFormRef)">确 定</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog title="分账比例" v-model="royaltyRateDialogState" width="580px">
            <el-form ref="royaltyRateFormRef" :model="royaltyRateForm" label-width="120px">
                <el-form-item label="服务商:" >
                    <div>{{ royaltyRateForm.wyf_service_name }}</div>
                </el-form-item>
                <el-form-item label="分账账号:" >
                    <div>{{ royaltyRateForm.wyf_account }}</div>
                </el-form-item>
                <el-form-item label="分账关系:" >
                    <div>{{ royaltyRateForm.wyf_relation_memo }}</div>
                </el-form-item>
                <el-form-item label="分账比例:" prop="royalty_rate">
                    <el-input v-model="royaltyRateForm.royalty_rate" placeholder="请输入分账比例">
                        <template #append>%</template>
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="royaltyRateDialogState = false">取 消</el-button>
                    <el-button type="primary" @click="saveRoyaltyRate(royaltyRateFormRef)">确 定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog title="花呗分期" v-model="periodDialogState" width="580px">
            <el-form ref="periodFormRef" :model="form" label-width="120px">
                <el-form-item label="商家花呗分期:" prop="huabei_status">
                    <el-switch v-model="form.huabei_status" :active-value="'2'" :inactive-value="'1'"></el-switch>
                </el-form-item>
                <template v-if="form.huabei_status == '2'">
                    <el-form-item v-for="(item,index) in form.period_charge_list" :key="index" :label="item.label + ':'" :prop="'form.period_charge_list['+index +'].charge_type'">
                        <el-select v-model="item.charge_type" placeholder="请选择">
                            <el-option v-for="item in dict['charge_type_list']" :key="item.value" :label="item.text" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="periodDialogState = false">取 消</el-button>
                    <el-button type="primary" @click="savePeriod(periodFormRef)">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed ,onMounted, nextTick, getCurrentInstance } from 'vue'
import { InfoFilled, Plus, Search, Hide, View, Close  } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import cookies from "libs/cookies";

import { assign } from 'lodash'

import { getHuabeiList,
         getHuabeiDetail,
         setHuabeiAuth,
         openHuabeiPay,
         openHuabeiRoyalty,
         getHuabeiRoyaltyRelation,
         setHuabeiRoyaltyRate,
         setHuabeiPeriod } from 'services/shop'

import systemStore from '@/store/modules/system'

const baseUrl = import.meta.env.GZG_BASE_URL;

const token = cookies.get("token");

const authFormRef = ref<FormInstance>();
const payFormRef = ref<FormInstance>();
const royaltyRateFormRef = ref<FormInstance>();
const periodFormRef = ref<FormInstance>();

const formRules = reactive<FormRules>({
    auth_app_id:[{ required: true, message: '请输入授权应用id', trigger: 'blur' }],
    auth_token:[{ required: true, message: '请输入授权token', trigger: 'blur' }],
    h5_web_url:[{ required: true, message: '请输入h5网站地址', trigger: 'blur' }],
    h5_home_screenshot:[{ required: true, message: '请上传h5网站首页截图', trigger: 'change' }],
    h5_item_screenshot:[{ required: true, message: '请上传h5网站商品截图', trigger: 'change' }],
    h5_pay_screenshot:[{ required: true, message: '请上传h5网站支付页截图', trigger: 'change' }],
});

const royaltyRateForm = ref({
    seller_id:'',
    wyf_service_name:'',
    wyf_account:'',
    wyf_relation_memo:'',
    royalty_rate:''
})

const form = ref({
    seller_id: '', //商家id
    company_name: '', //公司名称
    merchant_pid: '', //支付宝商户pid
    auth_app_id: '', //授权应用id
    auth_token: '', //授权token
    auth_expire_at: '', //授权到期时间
    h5_web_url: '', //h5网站地址
    web_remark: '', //网站备注
    h5_home_screenshot: '', //h5网站首页截图
    h5_item_screenshot: '', //h5网站商品截图
    h5_pay_screenshot: '', //h5网站支付页截图
    h5_extra_pic: '', //h5网站备注图
    wyf_service_name: '', //服务商名称
    wyf_account: '', //分账账号
    wyf_relation_memo: '', //分账关系
    royalty_rate: '', //分账比例
    huabei_status: '', //花呗状态：1未开通 2已开通
    period_charge_list: <any>[] //分期手续费组
})

const h5_home_screenshot_list = ref<any>([])
const h5_item_screenshot_list = ref<any>([])
const h5_pay_screenshot_list = ref<any>([])
const h5_extra_pic_list = ref<any>([])

const authDialogState = ref(false)
const payDialogState = ref(false)
const royaltyDialogState = ref(false)
const periodDialogState = ref(false)
const royaltyRateDialogState = ref(false)

const searchForm = reactive({
    company_name:'',
    short_name:''
})

const searchConfig = reactive([{
    id:'company_name',
    label:'商户全称',
    placeholder:'请输入商户全称',
    type: 'input'
},{
    id:'short_name',
    label:'商户简称',
    placeholder:'请输入商户简称',
    type: 'input'
}])

const listData = reactive({
    total:0,
    data:<any>[]
})

const params = ref({
    company_name:'',
    short_name:'',
    page_size:  20,
    page:  1,
})

const search = (searchParams:any) => {

    assign(params.value, searchParams)

    params.value.page = 1

    getList()
}

const handleSizeChange = (val: number) => {
    params.value.page_size = val
    params.value.page = 1
    getList();
}

const handleCurrentChange = (val:number) => {
    params.value.page = val
    getList()
} 

const getList = async () => {
    const res  = await getHuabeiList(params.value)
    listData.total = parseInt(res.total_rows)
    listData.data = res.items || []
}

const getDetail = async (seller_id:string, callback:Function) => {
    const res = await getHuabeiDetail({seller_id})
    form.value  = res
    callback()
}

const handleImgRemove = (file:any, key:string) => {
    form.value[key] = '';

}

const handleImgSuccess = (data:any, key:string) => {
    if (data.code == 0) {
        form.value[key] = data.data.file[0].absolute_path;
    }
}

const openAuthDialog = (row:any) => {
   getDetail(row.seller_id, () => {
       authDialogState.value = true
   })
}

const saveAuth = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            setHuabeiAuth(form.value).then(res => {
                ElMessage.success('操作成功')
                authDialogState.value = false
                getList()
                
            })
        }
    })
    
}

const savePay = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            openHuabeiPay(form.value).then(res => {
                ElMessage.success('操作成功')
                payDialogState.value = false
                getList()
                
            })
        }
    })
}

const saveRoyaltyRate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            setHuabeiRoyaltyRate(royaltyRateForm.value).then(res => {
                ElMessage.success('操作成功')
                royaltyRateDialogState.value = false
            })
        }
    })
}

const savePeriod = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            setHuabeiPeriod(form.value).then(res => {
                ElMessage.success('操作成功')
                periodDialogState.value = false
                getList()
                
            })
        }
    })
}

const openPayDialog = (row:any) => {
    getDetail(row.seller_id, () => {
        payDialogState.value = true
    })
}

const openRoyaltyDialog = (row:any) => {
    openHuabeiRoyalty({
        seller_id:row.seller_id
    }).then(res => {
        ElMessage.success('操作成功')
        getList()
    })
}

const openRoyaltyRateDialog = (row:any) => {
    getHuabeiRoyaltyRelation({seller_id:row.seller_id}).then(res => {
        res['seller_id'] = row.seller_id
        royaltyRateForm.value = res
        royaltyRateDialogState.value = true

    })
    
}

const openPeriodDialog = (row:any) => {
    getDetail(row.seller_id, () => {
        periodDialogState.value = true
    })
}

const dict = computed(() => {
    return systemStore().dict
})

onMounted(() => {
    getList()
})
</script>